package com.tony.demo.ui.user;

import android.content.Intent;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.puhui.lib.http.HttpParams;
import com.puhui.lib.http.nativeapi.HttpUrlConnectionProxy;
import com.puhui.lib.http.retrofit.RequestResponse;
import com.puhui.lib.utils.encrypt.MD5Util;
import com.puhui.lib.widgets.listener.TextWatcherImpl;
import com.tony.demo.DemoApplication;
import com.tony.demo.R;
import com.tony.demo.bean.UserInfo;
import com.tony.demo.mvp.presenter.impl.LoginPresenter;
import com.tony.demo.mvp.views.ILoginView;
import com.tony.demo.ui.base.BaseActivity;

import org.json.JSONObject;

/**
 * 登录页面
 *
 * @author jiaohongyun
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements ILoginView, OnClickListener {

    private EditText nameEditText;  //用户名输入框
    private EditText pwdEditText;  //密码输入框
    private Button loginBtn;  //登录按钮
    private ImageView eye_iv;

    /**
     * 是否忘记手势密码， 是则需要删除手势密码
     */
    protected boolean forgetLockPwd = false;
    private boolean isHidden = true;
    private String phoneNumber;

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        phoneNumber = intent.getStringExtra("phoneNumber");
        if (!TextUtils.isEmpty(phoneNumber)) {
            nameEditText.setText(phoneNumber);
            pwdEditText.requestFocus();
        }
    }

    /**
     * 初始化页面
     */
    protected void initView() {
        forgetLockPwd = getIntent().getBooleanExtra("forgetLockPwd", false);
        phoneNumber = getIntent().getStringExtra("phoneNumber");

        ((TextView) findViewById(R.id.title_text)).setText(R.string.login);
        nameEditText = findViewById(R.id.login_name);
        pwdEditText = findViewById(R.id.login_pwd);
        loginBtn = findViewById(R.id.login_ok_btn);
        eye_iv = findViewById(R.id.eye_iv);

        findViewById(R.id.login_forget_pwd).setOnClickListener(this);
        loginBtn.setOnClickListener(this);
        findViewById(R.id.register_tv).setOnClickListener(this);

        if (!TextUtils.isEmpty(phoneNumber)) {
            nameEditText.setText(phoneNumber);
        }
        nameEditText.addTextChangedListener(new TextWatcherImpl() {
            @Override
            public void afterTextChanged(Editable s) {
                setButtonBackground();
            }
        });

        pwdEditText.addTextChangedListener(new TextWatcherImpl() {
            @Override
            public void afterTextChanged(Editable s) {
                setButtonBackground();
            }
        });

        eye_iv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isHidden) {
                    //设置EditText文本为可见的
                    pwdEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    eye_iv.setBackgroundResource(R.mipmap.eye);
                } else {
                    //设置EditText文本为隐藏的
                    pwdEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    eye_iv.setBackgroundResource(R.mipmap.eye2);
                }
                isHidden = !isHidden;
                pwdEditText.postInvalidate();

                CharSequence charSequence = pwdEditText.getText();
                Spannable spanText = (Spannable) charSequence;
                Selection.setSelection(spanText, charSequence.length());
            }
        });

        loginBtn.setEnabled(true);
    }

    private void setButtonBackground() {
        String checkName = nameEditText.getText().toString();
        String checkPwd = pwdEditText.getText().toString();
        if (!checkName.equals("") && !checkPwd.equals("")) {
            loginBtn.setBackgroundResource(R.drawable.common_btn_enable);
        } else {
            loginBtn.setBackgroundResource(R.drawable.common_blue_btn_bg);
        }
    }

    @Override
    public void onClick(View v) {
        if (checkClick(v.getId())) {
            switch (v.getId()) {
                case R.id.login_ok_btn: // 登录
                    nameEditText.setText("13537839115");
                    pwdEditText.setText("tang@jian@1228");

                    String loginName = nameEditText.getText().toString();
                    String loginPwd = pwdEditText.getText().toString();
                    if (validate()) {
                        presenter.startLogin(loginName, loginPwd);
                    }
                    break;
            }
        }
    }

    /**
     * 登录
     */
    private void startLogin() {
        HttpParams httpParams = new HttpParams();
        long time = System.currentTimeMillis() - DemoApplication.getInstance().diffTime;

        String flag = MD5Util.getFlag(nameEditText.getText().toString(), pwdEditText.getText().toString(), time + "");
        final String password = pwdEditText.getText().toString();
        final String accountName = nameEditText.getText().toString();
        httpParams.put("flag", flag);
        httpParams.put("accountName", accountName);
        httpParams.put("time", time);
        httpParams.put("password", password);

        startLoading();
        HttpUrlConnectionProxy.getInstance().post(this, "", httpParams, new RequestResponse<String>() {
            @Override
            public void onSuccess(String code, String message, String result) {
                stopLoading();
                //保存用户信息
//                saveUserInfo(result, accountName, password);
                //主要用于更新登录状态和更新客户端和服务器端时间差
            }

            @Override
            public void onFailure(Throwable t) {
                super.onFailure(t);
                stopLoading();
            }
        });
    }

    /**
     * 解析并保存用户对象
     */
    private void saveUserInfo(JSONObject result, String accountName, String password) {
    }

    /**
     * 参数校验
     */
    private boolean validate() {
        if (nameEditText.getText().toString().isEmpty() || nameEditText.getText().toString().trim().equals("")) {
//            AlertDialogUtil.alert(this, "用户名不能为空");
            nameEditText.findFocus();
            return false;
        }

        String password = pwdEditText.getText().toString();
        if (password.isEmpty() || password.trim().equals("")) {
//            AlertDialogUtil.alert(this, "密码不能为空");
            pwdEditText.findFocus();
            return false;
        }
        return true;
    }

    @Override
    public void onLoginSuccess(UserInfo userInfo) {

    }
}
